import { createApp } from "vue";
import App from "./App.vue";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";

import router, { setMainAppToken } from "./router";
import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";

let app = createApp(App);
app.use(ElementPlus);

const render = (props = {}) => {
  const { container } = props;
  app = createApp(App);

  // 使用路由
  app.use(router);

  app.mount(container ? container.querySelector("#app") : "#app");
};

// 独立运行时
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  // 检查localStorage中是否有存储的token
  const savedToken =
    localStorage.getItem("mainAppToken") || localStorage.getItem("subAppToken");
  if (savedToken) {
    // 如果有存储的token，设置到路由中
    setMainAppToken(savedToken);
  }
  render();
}

// 作为子应用运行时
renderWithQiankun({
  mount(props) {
    // 获取token
    const token = props.getToken ? props.getToken() : "";
    console.log("从主应用获取的token:", token);

    // 设置token到路由中
    if (token) {
      setMainAppToken(token);
    }
    render(props);
  },
  bootstrap() {
    console.log("vue3-vite bootstrap");
  },
  unmount(props) {
    console.log("vue3-vite unmount", props);
    app.unmount();
  },
  update(props) {
    console.log("vue3-vite update", props);
    // 如果props中有更新的token，也更新到路由中
    const token = props.getToken ? props.getToken() : "";
    if (token) {
      setMainAppToken(token);
    }
  },
});
app = null;
